package com.sinochem.yunlian.ship.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class CustomResponseErrorHandler implements ResponseErrorHandler {
    private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
    public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
//        if (clientHttpResponse.getStatusCode() != HttpStatus.OK) {
//            log.debug("Status code: " + clientHttpResponse.getStatusCode());
//            log.debug("Response" + clientHttpResponse.getStatusText());
//            String result = IOUtils.toString(clientHttpResponse.getBody());
//            log.debug(result);
//
//            if (clientHttpResponse.getStatusCode() == HttpStatus.FORBIDDEN) {
//                log.debug("Call returned a error 403 forbidden resposne ");
//                return true;
//            }
//        }
        return errorHandler.hasError(clientHttpResponse);
    }

    public void handleError(ClientHttpResponse response) throws IOException {
        byte[] bytes = IOUtils.toByteArray(response.getBody());
        throw  new HttpClientErrorException(response.getStatusCode(), response.getStatusText(),
                                                                        bytes, StandardCharsets.UTF_8);
    }
}